--- 此脚本的环境：  nginx 内部，不是运行在 redis 内部


local restOut = { respCode = 0, resp_msg = "proxy成功", datas = {} };
local errorOut = { respCode = -1, resp_msg = "proxy失败", datas = {} };

--导入自定义的基础模块
--local basic = require("luaScript.module.common.basic");

--读取get参数
--local uri_args = ngx.req.get_uri_args()
--读取post参数
ngx.req.read_body();
--local uri_args = ngx.req.get_post_args()
local requestBody = ngx.req.get_body_data(); --获取消息体

--ngx.say(data)

-- [ seckillSkuId:1,seckillSkuId:3,seckillSkuId:4]
local args = cjson.decode(requestBody);

--优先从缓存获取，否则访问上游接口

local requestKey ={
    exposedKey="1156308907673518080",
    newStockNum= 10000,
    seckillSkuId= 1,
    seckillToken= "1156308907673518080",
    userId= 1
};
local out = {  };
local sku_cache = ngx.shared.sku_cache

for i, v in ipairs(args) do

    local r = {}
    local skuCache = nil;
    string.gsub(v, "[^:]+", function(w) table.insert(r, w) end)

    ngx.log(ngx.DEBUG, "cache " .. tostring(v) .. " cache region" .. tostring(r[1]) .. " cache key" .. tostring(r[2]))

    requestKey.seckillSkuId = r[2];
   local   skuIdCacheKey= tostring( r[2]);
    local str = cjson.encode(requestKey);
    --ngx.log(ngx.DEBUG, "requestKey " .. str)


    --回源上游接口,比如Java 后端rest接口
    local res = ngx.location.capture("/stock-provider/api/seckill/sku/detail/v1", {
        method = ngx.HTTP_POST,
        body = str, -- 重要：将请求参数
        always_forward_body = false, -- 也可以设置为false 仅转发put和post请求方式中的body.
    })

    if res.status == ngx.HTTP_OK then
        --返回上游接口的响应体 body
        skuCache = res.body;
        ngx.log(ngx.DEBUG, "skuCache=" .. skuCache)

        --单位为s
        sku_cache:set(skuIdCacheKey, skuCache, 100 * 60 * 60)
        table.insert(out, skuCache);
    else
        table.insert(out, res.body);
    end

end
ngx.say(out);

